package com.mk.legoscans2.data;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

import com.google.android.gcm.GCMRegistrar;
import com.mk.legoscans2.LegoScans3Application;
import com.mk.legoscans2.R;
import com.mk.legoscans2.Utils;
import com.mk.legoscans2.activities.StartActivity;

public class NotificationService {
	
	ApplicationPreferences _applicationPreferences;
	
	public NotificationService(ApplicationPreferences applicationPreferences){
		_applicationPreferences = applicationPreferences;
	}
	
	public void register(Context context, String regId, String account) {
		String response = Utils.postToWebApi("/register/json/" + regId, "source=android&account=" + account);

		if(Boolean.parseBoolean(response))
			_applicationPreferences.setGcmRegistrationVersion(LegoScans3Application.getApplicationVersionCode());
		else
			GCMRegistrar.unregister(context);
	}

	public boolean unRegister(String regId) {
		String response = Utils.postToWebApi("/unregister/json/" + regId, "source=android");
		_applicationPreferences.setGcmRegistrationVersion(-1);
		return Boolean.parseBoolean(response);
	}

	public void createNotification(Context context, String title, String message) {
		// Prepare intent which is triggered if the notification is selected
	    Intent intent = new Intent(context, StartActivity.class);
	    PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);

	    try{
	    // Build notification
	    Notification noti = new NotificationCompat.Builder(context)
	        .setContentTitle(title)
	        .setContentText(message)
	        .setSmallIcon(R.drawable.ic_launcher)
	        .setContentIntent(pIntent).build();
	    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
	    
	    // Hide the notification after its selected
	    noti.flags |= Notification.FLAG_AUTO_CANCEL;

	    notificationManager.notify(0, noti);
	    }catch(Exception ex){
	    	ex.printStackTrace();
	    }
	}
}
